/* eslint-disable react/prop-types */

import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';

import SidebarComponent from './sidebar/SidebarComponent';
import HeaderComponent from './header/HeaderComponent';

import * as rootAction from './RootAction';

@connect(mapStateToProps, buildActionDispatcher)
export default class RootComponent extends React.Component {
  constructor(props) {
    super(props);
    this.onClickOutside = this.onClickOutside.bind(this);
  }

  onClickOutside() {
    this.props.rootAction.hideSidebarDisplay();
  }

  componentDidMount() {
    const { rootAction } = this.props;
    rootAction.loginFromCookies();
    rootAction.detectEnvironment();
    rootAction.getCategories();
    rootAction.getMyWorkStats();
  }

  render() {
    const sidebarStyle = {
      left: this.props.sidebarVisibility ? 0 : -376,
    };
    const rightBodyClass = this.props.location.pathname === '/' ? 'right' : 'right body-content';
    return (
      <div className="root" onClick={this.onClickOutside}>
        <HeaderComponent
          sidebarVisibility={this.props.sidebarVisibility}
          userProfile={this.props.userProfile}
          rootAction={this.props.rootAction}
          router={this.props.router}
        />
        <div className="main">
          <div className="left" style={sidebarStyle}>
            <SidebarComponent
              categories={this.props.categories}
              publishedCount={this.props.publishedCount}
              uploadsCount={this.props.uploadsCount}
              likesCount={this.props.likesCount}
              rootAction={this.props.rootAction}
            />
          </div>
          <div className={rightBodyClass}>
            {this.props.children}
          </div>
        </div>
      </div>
    );
  }
}

function mapStateToProps(state) {
  const { Root, My } = state;
  const { categories, sidebarVisibility } = Root;
  const publishedCount = My.Published.publishedCount;
  const uploadsCount = My.Uploads.uploadsCount;
  const likesCount = My.Likes.likesCount;
  const userProfile = My.Session.profile;

  return { sidebarVisibility, categories, publishedCount, uploadsCount, likesCount, userProfile };
}

function buildActionDispatcher(dispatch) {
  return {
    rootAction: bindActionCreators(rootAction, dispatch),
  };
}
